package com.example.rabbitcloud.consumer;

import com.example.rabbitcloud.exchange.Produce;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.cloud.stream.messaging.Sink;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessagingException;
import org.springframework.messaging.SubscribableChannel;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.UnsupportedEncodingException;

/**
 * @author cxx
 * @create 2020-02-21 21:07
 **/
@Component
public class MyConsumer {

    @Autowired
    private SimpleMessageReceiver sink;

    /**
     * 使用不同的形式来消费
     */

    @PostConstruct
    public void process(){

        SubscribableChannel channel = sink.testChannel ();

        channel.subscribe (new MessageHandler(){
            @Override
            public void handleMessage(Message<?> message) throws MessagingException {
                byte[] content = (byte[]) message.getPayload();
                try {
                    System.out.println("接受到消息：" + new String(content,"UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @StreamListener(Produce.OUTPUT)  // Spring Cloud Stream 注解驱动
    public void onMessage(byte[] data) {
        System.out.println("onMessage(byte[]): " + new String(data));
    }

}
